package org.zerofwk.example.datastruct.linklist;

/**
 * 约瑟夫环，测试单链表
 */
public class JosepfuCircleTest {
    public static void main(String[] args) {
        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        circleSingleLinkedList.addBoy(5);
        circleSingleLinkedList.show();

        System.out.println("\n约瑟夫出圈序号：");
        circleSingleLinkedList.countBoy(1,2,5);
    }
}

class CircleSingleLinkedList {

    private Boy first = new Boy(-1);

    public void addBoy(int nums) {
        if (nums < 1) {
            System.out.println("nums的值不正确。");
            return;
        }
        Boy curBoy = null;
        for (int i = 1; i <= nums; i++) {
            Boy boy = new Boy(i);
            if (i == 1) {
                first = boy;
                curBoy = boy;
                boy.setNext(first);
            } else {
                curBoy.setNext(boy);
                boy.setNext(first);
                curBoy = boy;
            }
        }
    }

    public void show() {
        if (first == null) {
            System.out.println("链表是空的。");
            return;
        }
        Boy curBoy = first;
        while (true) {
            System.out.printf("圈的序号是：%d \n", curBoy.getNo());
            if (curBoy.next == first) {
                break;
            }
            curBoy = curBoy.next;
        }

    }

    /**
     * @param startNo   起始编号
     * @param countStep 步长
     * @param boyNums   圈内总数
     */
    public void countBoy(int startNo, int countStep, int boyNums) {
        if (first == null || startNo < 1 || startNo > boyNums) {
            System.out.println("输入的参数有误。");
            return;
        }

        Boy helper = first;
        while (helper.getNext() != first) {
            helper = helper.getNext();
        }
        for (int i = 0; i < startNo-1; i++) {
            first = first.getNext();
            helper = helper.getNext();
        }

        while (helper != first){
            for (int i = 0; i < countStep-1; i++) {
                first = first.getNext();
                helper = helper.getNext();
            }
            System.out.printf("出圈的编号是：%d\n",first.getNo());
            first = first.getNext();
            helper.setNext(first);
        }
        System.out.printf("最后一个出圈编号是：%d\n",first.getNo());

    }

    private class Boy {
        private int no;
        private Boy next;

        public Boy(int no) {
            this.no = no;
            this.next = null;
        }

        public int getNo() {
            return no;
        }

        public void setNo(int no) {
            this.no = no;
        }

        public Boy getNext() {
            return next;
        }

        public void setNext(Boy next) {
            this.next = next;
        }
    }
}

